
package org.example.news_check.Controller;

import org.example.news_check.Pojo.AjaxResult;
import org.example.news_check.Pojo.articles;
import org.example.news_check.Pojo.likeArticles;
import org.example.news_check.Service.ArticlesService;
import org.example.news_check.Service.LikeArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticlesService articlesService;

    @Autowired
    private LikeArticlesService likeArticlesService;

    @PostMapping("articleLike")
    public AjaxResult addUpdateLikeArticles(@RequestBody likeArticles likeArticles) {
        //查询文章详情
        articles article = articlesService.selectArticlesById(Long.valueOf(likeArticles.getArticleId()));
        if (article == null) {
            return AjaxResult.error("文章不存在");
        }
        try {//查询文章点赞记录  根据发表人id和文章id查询进行查询
            likeArticles articlesLikeArticles = likeArticlesService.selectMemberByMemberId(likeArticles.getMemberId(), likeArticles.getArticleId());
            //判断点赞记录是否为空，如何不为空就取消点赞 并且点赞-1;  如果为空就添加点赞进行点赞+1操作
            if (articlesLikeArticles != null) {
                Integer currentLikeCount = article.getLikeCount();
                currentLikeCount = currentLikeCount == null ? 0 : currentLikeCount;
                Long likeCount = Long.valueOf(currentLikeCount - 1);
                article.setLikeCount(likeCount < 0 ? 0 : likeCount.intValue());
                articlesService.updateArticles(article);
                // 取消点赞记录
                likeArticlesService.updateLikeArticles(likeArticles);
                return AjaxResult.success("取消点赞成功");



            } else {
                //添加点赞
                article.setLikeCount(article.getLikeCount() + 1);
                articlesService.updateArticles(article);
                //添加点赞记录
                likeArticlesService.saveLikeArticles(likeArticles);
                return AjaxResult.success("点赞成功");

            }
//            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常，请稍后再试");
        }
    }

    @GetMapping("/likecount/{articleId}")//获取点赞数
    public int getLikeCount(@PathVariable Long articleId) {
        articles article = articlesService.selectArticlesById(articleId);
        int likeCount = articlesService.selectLikeCount(articleId);
        return articlesService.selectLikeCount(articleId);
    }


}
